package apiv1

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/go-playground/validator/v10"
	"go-shop-admin/internal/validate"
	"go-shop-admin/pkg/e"
	"go-shop-admin/pkg/serializer"
	"strconv"
	"strings"
)

//公用方法

// Validators  公共验证
func Validators(err error) *serializer.Response {
	// 获取validator.ValidationErrors类型的errors
	errs, ok := err.(validator.ValidationErrors)
	if !ok {
		// 非validator.ValidationErrors类型错误直接返回
		return serializer.NewResponse(e.InvalidParams, e.TipsOk, fmt.Sprint(err), nil)
	}

	//判断json类型是否正确
	if _, ok := err.(*json.UnmarshalTypeError); ok {
		return serializer.NewResponse(e.ErrorJsonType, e.TipsOk, fmt.Sprint(err), nil)
	}

	// validator.ValidationErrors类型错误则进行翻译
	return serializer.NewResponse(e.InvalidParams, e.TipsOk, e.TipsNil, validate.RemoveTopStruct(errs.Translate(validate.GetValidatorTrans())))
}

// GetRestfulApiId  检验id 获取从 RESTful API 传递过来的id  scene 场景 1 修改/获取  2 删除ids
func GetRestfulApiId(idString string, scene uint) (idUint uint, ids []string, err error) {
	if idString == "" {
		return 0, nil, errors.New("id不可为空")
	}

	if scene == 2 {
		return 0, strings.Split(idString, ","), nil
	} else {
		// 修改/获取  /{id}
		id, err := strconv.Atoi(idString)
		if err != nil {
			return 0, nil, err
		}
		return uint(id), nil, nil
	}
}
